package io.growing.adaptor.common.async;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName BoundedPriorityBlockingQueue @Description 有界优先队列 @Author wangjiu @Date 2021/12/13 3:38
 * 下午
 */
public class BoundedPriorityBlockingQueue extends PriorityBlockingQueue {

    private final int capacity;

    private final ReentrantLock lock;

    public BoundedPriorityBlockingQueue(int capacity) {
        super(capacity);
        this.capacity = capacity;
        this.lock = new ReentrantLock();
    }

    @Override
    public boolean offer(Object o) {
        lock.lock();
        try {
            if (super.size() >= capacity) {
                return false;
            }
            return super.offer(o);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public boolean offer(Object o, long timeout, TimeUnit unit) {
        lock.lock();
        try {
            if (super.size() >= capacity) {
                return false;
            }
            return super.offer(o, timeout, unit);
        } finally {
            lock.unlock();
        }
    }
}
